package com.mall.order.biz.handler;

import com.mall.commons.tool.exception.BizException;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.user.IMemberService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.QueryMemberRequest;
import com.mall.user.dto.QueryMemberResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 *  ciggar
 * create-date: 2019/8/1-下午4:47
 *
 */
@Slf4j
@Component
public class ValidateHandler extends AbstractTransHandler {

    // 配置false之后无需检查该service是否有在注册中心注册 -- 只在调用时候去注册中心寻找
    // 所以在启动order_provider的时候就可以不需要关注user_provider是否有没有启动
    // 可以单独调用 -- 启动检查的作用(check = false)

    @Reference(check = false)
    private IMemberService memberService;

    /**
     * 验证用户合法性
     * @return
     */

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    public boolean handle(TransHandlerContext context) {
        // 转个型
        CreateOrderContext createOrderContext = (CreateOrderContext) context;
        QueryMemberRequest request = new QueryMemberRequest();
        request.setUserId(createOrderContext.getUserId());

        QueryMemberResponse response = memberService.queryMemberById(request);

        // 判断一下
        if (response.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())){
            if (!response.getUsername().equals(createOrderContext.getUserName())){
                // 抛出一个业务异常 -- 与response中的错误信息对应起来
                throw new BizException(response.getCode(),response.getMsg());
            }

            // 还有两个参数未设定 -- 购买用户的昵称 -- 生成订单商品的ID list
            createOrderContext.setBuyerNickName(response.getUsername());
            // createOrderContext.setBuyProductIds(response.getId());
        }
        return true;
    }
}
